package com.ruoyi.chat.websocket;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.chat.domain.ChatCompletionRequest;
import com.ruoyi.chat.domain.ChatRecord;
import com.ruoyi.chat.domain.Message;
import com.ruoyi.chat.domain.MessageBody;
import com.ruoyi.chat.service.IChatRecordService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.websocket.WebSocketUsers;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.BufferedSource;
import okio.Okio;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SiliconFlowApiClient {
    private static final String API_URL = "https://api.siliconflow.cn/v1/chat/completions";
    private static final String AUTH_TOKEN = "Bearer sk-ntxjanomzhbbjgesvtlpsnvicoyrapktdbkwnlqdehineeui"; // 替换为实际的token
    private final OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(40, TimeUnit.SECONDS) // 连接超时设置为20秒
            .writeTimeout(200, TimeUnit.SECONDS) // 写入超时设置为30秒
            .readTimeout(200, TimeUnit.SECONDS) // 读取超时设置为30秒
            .build();;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private IChatRecordService chatRecordService;

    public String callApi(ChatCompletionRequest request,Session session) throws IOException {
        // 构建请求体
        RequestBody body = RequestBody.create(MediaType.parse("application/json"),objectMapper.writeValueAsString(request));

        // 构建请求
        Request httpRequest = new Request.Builder()
                .url(API_URL)
                .header("Authorization", AUTH_TOKEN)
                .header("Content-Type", "application/json")
                .post(body)
                .build();

        // 发送请求并获取响应
        try (Response response = client.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            return doHandleLineContent(request,response,session);
        } catch (Exception e) {
            //log.err("sendRequest请求执行失败.{1}", e);
            System.out.println("over: ");
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 按行处理结果
     */
    private String doHandleLineContent(ChatCompletionRequest request, Response response,Session session) throws IOException {
        if(response.body() == null){
            return null;
        }

        int index= 0;
        int count= 0;

        String line = "";
        BufferedSource source = Okio.buffer(response.body().source());
        StringBuilder sb = new StringBuilder();
        while ((line = source.readUtf8Line()) != null) {
            //log.info("doHandleLineContent 获取DiFy的没有data的时候响应报文---->>content:{}", line);
            String lineNew = "";
            if (line.startsWith("data: ") && !line.equals("data: [DONE]")) {
                //System.out.println(line);
                lineNew = line.replace("data: ", "");
                ChatCompletionResponse chatCompletionResponse = JSONObject.parseObject(lineNew, ChatCompletionResponse.class);
                if (chatCompletionResponse != null && chatCompletionResponse.getChoices() != null
                        && !chatCompletionResponse.getChoices().isEmpty()) {
                    Choice choice = chatCompletionResponse.getChoices().get(0);
                    if (choice != null && choice.getDelta() != null && choice.getDelta().getContent()!= null) {
                        String content = choice.getDelta().getContent();
                        if (StringUtils.isNotEmpty(content)) {
                            sb.append(content);
                            //System.out.println(sb.toString());
                            MessageBody messageBody = request.getMessageBody();
                            messageBody.setMessage(content);
                            WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(messageBody));
                        }
                    }
                }
            }
        }

        return sb.toString();
    }

    public String funcationCall(String message,Session session) {
        try {
            MessageBody messageBody = JSONObject.parseObject(message, MessageBody.class);
            insertChatRecord(messageBody,"user");

            List<Message> msgList = new ArrayList<>();
            ChatRecord queryChatRecord = new ChatRecord();
            queryChatRecord.setSessionId(messageBody.getSessionId());
            List<ChatRecord> chatRecords = chatRecordService.selectChatRecordList(queryChatRecord);
            for (ChatRecord record : chatRecords) {
                Message msg = new Message();
                msg.setRole(record.getRoleName());
                msg.setContent(record.getContent());
                msgList.add(msg);
            }

            // 构建请求
            ChatCompletionRequest request = new ChatCompletionRequest();
            request.setModel("Qwen/Qwen3-8B");
            request.setMaxTokens(512);
            request.setTemperature(0.7);
            request.setTopP(0.7);
            request.setStream(true);
            request.setMessages(msgList);
            request.setMessageBody(messageBody);

            // 调用API
            String response = callApi(request, session);
            System.out.println("Response: " + response);
            messageBody.setMessage(response);
            insertChatRecord(messageBody,"assistant");
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private void insertChatRecord(MessageBody messageBody,String roleName) {
        ChatRecord chatRecord = new ChatRecord();
        chatRecord.setContent(messageBody.getMessage());
        chatRecord.setSessionId(messageBody.getSessionId());
        chatRecord.setContentType(roleName);
        chatRecord.setRoleName(roleName);
        chatRecord.setSender(messageBody.getUserName());
        chatRecordService.insertChatRecord(chatRecord);
    }
}

// 响应类
@Data
class ChatCompletionResponse {
    private String id;
    private String object;
    private long created;
    private String model;
    private List<Choice> choices;
    private Usage usage;
    private String systemFingerprint;
}

@Data
class Choice {
    private int index;
    private Delta delta;
    private String finishReason;
}

@Data
class Delta {
    private String content;
    private String reasoningContent;
    private String role;
}

@Data
class Usage {
    private int promptTokens;
    private int completionTokens;
    private int totalTokens;
    private CompletionTokensDetails completionTokensDetails;
}

@Data
class CompletionTokensDetails {
    private int reasoningTokens;
}